﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Microsoft.Win32;

namespace GeoSwarm_Editor
{
    class UpdateChecker
    {
        private string currentVersion;

        public UpdateChecker(string currentVersion)
        {
            this.currentVersion = currentVersion;
        }

        public bool UpdateAvailable()
        {
            string result = HttpPost("http://example.com/GDSEver.php", string.Empty);
            if (result != "Exception")
                AddToReg(result);
            else
                return CheckReg_UpdateAvailable(currentVersion);
            if (result != currentVersion)
                return true;
            else
                return false;
        }

        private void AddToReg(string latestVer)
        {
            RegistryKey regKey = Registry.CurrentUser;
            regKey = regKey.CreateSubKey("Software\\GDSE");
            regKey.SetValue("newestVersion", latestVer);
        }

        private bool CheckReg_UpdateAvailable(string currentVer)
        {
            RegistryKey regKey = Registry.CurrentUser;
            regKey = regKey.CreateSubKey("Software\\GDSE");
            if (regKey.GetValue("newestVersion") == null)
                return false;
            else if (regKey.GetValue("newestVersion").ToString() != currentVer)
                return true;
            else
                return false;
        }

        private string HttpPost(string uri, string parameters)
        {
            // parameters: name1=value1&name2=value2	

            WebRequest webRequest = WebRequest.Create(uri);

            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method = "POST";
            byte[] bytes = Encoding.ASCII.GetBytes(parameters);
            Stream os = null;
            try
            {
                // send the Post
                webRequest.ContentLength = bytes.Length;   //Count bytes to send
                os = webRequest.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);         //Send it
            }
            catch (WebException)
            {
                return "Exception";
            }
            finally
            {
                if (os != null)
                {
                    os.Close();
                }
            }

            try
            {
                // get the response
                WebResponse webResponse = webRequest.GetResponse();
                if (webResponse == null)
                {
                    return null;
                }
                StreamReader sr = new StreamReader(webResponse.GetResponseStream());
                return sr.ReadToEnd().Trim();
            }
            catch (WebException)
            {
                return "Exception";
            }
        }

    }
}
